﻿using DTcms.Core.IServices;
using DTcms.Core.IServices.WeChatPay;
using DTcms.Core.Model.WeChatPay;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DTcms.Core.API.Controllers
{
    [Area("api")]
    [Route("api/wechatpay/notify")]
    [ApiController]
    public class WeChatPayNotifyController : ControllerBase
    {
        private readonly IWeChatPayNotify _weChatPayNotify;
        private readonly IMemberRechargeService _memberRechargeService;
        public WeChatPayNotifyController(IWeChatPayNotify weChatPayNotify, IMemberRechargeService memberRechargeService)
        {
            _weChatPayNotify = weChatPayNotify;
            _memberRechargeService = memberRechargeService;
        }

        /// <summary>
        /// 支付成功回调
        /// 示例：/api/wechatpay/notify/transactions/1
        /// </summary>
        [HttpPost("transactions/{paymentId}")]
        public async Task<IActionResult> Transactions([FromRoute] int paymentId)
        {
            bool result = false; //处理状态
            var notify = await _weChatPayNotify.ConfirmAsync(Request, paymentId);
            if (notify.TradeState == "SUCCESS")
            {
                //判断充值订单还是商品订单
                if (notify.OutTradeNo.StartsWith("RN"))
                {
                    //修改充值订单状态
                    result = await _memberRechargeService.CompleteAsync(notify.OutTradeNo);
                }
            }
            //返回结果
            if (result)
            {
                return Ok(new WeChatPayNotifyResultDto());
            }
            return BadRequest(new WeChatPayNotifyResultDto()
            {
                Code = "FAIL",
                Message = "FAIL"
            });
        }

    }
}
